package com.eascs.archive.controller.v1;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.eascs.admin.common.vo.LoanApplyEntity;
import com.eascs.admin.common.vo.ModelResult;
import com.eascs.admin.o2o.badloan.service.O2oBadLoanService;
import com.eascs.admin.o2o.compensatory.entity.CompensatoryDataEnter;
import com.eascs.admin.o2o.compensatory.entity.DCUpdateData;
import com.eascs.admin.o2o.compensatory.service.O2oDCLoanService;
import com.eascs.admin.o2o.detail.service.LoanDetailService;
import com.eascs.admin.o2o.internal.entity.PubDditem;
import com.eascs.admin.o2o.internal.service.PubDditemService;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.archive.dao.ArchiveRecordDao;
import com.eascs.archive.dubbo.ArchiveTask;
import com.eascs.archive.entity.*;
import com.eascs.archive.service.ArchiveBorrowService;
import com.eascs.archive.service.ArchiveRecordService;
import com.eascs.archive.service.ArchiveService;
import com.eascs.archive.untils.ArchiveConstants;
import com.eascs.datalist.entity.O2oDataListEntity;
import com.eascs.datalist.service.O2oDataListService;
import com.eascs.dubbo.loan.service.LoanInfoServiceImpl;
import com.eascs.loan.service.O2oLoanService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.site.view.button.ShowButtonFilter;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTaskMain;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sequence.SequenceService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.WFRequestParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

@RestController(value="archiveRestControllerV1")
@RequestMapping("/archive/rest/v1")
public class ArchiveRestController extends BaseRestController {
	
	@Autowired
	private ArchiveRecordService archiveRecordService;
	@Autowired
	private ArchiveService archiveService;
	@Autowired
	private LoanInfoServiceImpl loanInfoService;
	@Autowired
	private O2oDataListService o2oDataListService;
	@Autowired
	private ArchiveTask archiveTask;
	@Autowired
	private ArchiveBorrowService archiveBorrowService;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	O2oLoanService o2oLoanService;
	@Reference
	private SequenceService sequenceService;
	@Reference
	WorkFlowService workFlowService;
	@Autowired
	private BaseUtils          baseUtils;
	@Autowired
	private LoanDetailService  loanDetailService;
	@Autowired
	private O2oLoanUserService o2oLoanUserService;
	@Autowired
	private O2oDCLoanService   o2oDCLoanService;
	@Autowired
	private ArchiveConstants   archiveConstants;
	@Autowired
	private ArchiveRecordDao   archiveRecordDao;
	@Autowired
	private O2oBadLoanService  service;
	@Autowired
	private PubDditemService pubDditemService;
	
	@Value("${o2o.admin.iframe.domain}")
	private String domain;
	@Value("${web.homeUrl}")
	private String serviceHomeUrl;
	@Value("${o2o.admin.service}")
	private String serviceUrl;
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	
	@RequestMapping(value = "/platformManager", method = RequestMethod.GET)
	public HtmlRestResult platformManager(String referId) {
		String loanapplyNo=referId;
		ModelResult<LoanApplyEntity> modelResult = loanInfoService.getLoanapplyInfo(loanapplyNo);
		LoanApplyEntity loanInfo = modelResult.getModel();
		String loanId=loanInfo.getLoanId();
		String bankName = loanInfo.getBankLoanName();
		String bankTypeId = ArchiveConstants.getBankTypeId(bankName);
		if (StringUtils.isNotBlank(bankTypeId)) {
			List<FieldEntity> archiveFields = archiveService.getFieldListByType(bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE);
			ArchiveRecordEntity archiveRecord=getFieldValue(archiveFields, loanapplyNo, bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE);
			//判断是否保存
			if(archiveFields!=null&&archiveRecord!=null&&archiveFields.size()>0){
				ViewContext.put("isSave", "show");
			}else{
				ViewContext.put("isSave", "hidden");
			}
			ViewContext.put("archiveFields", archiveFields);
			ViewContext.put("archiveRecord", archiveRecord);
			ViewContext.put("bankTypeId", bankTypeId);
			ViewContext.put("loanapplyNo", loanapplyNo);
			ViewContext.put("loanId", loanId);
			ViewContext.put("formTypeId", ArchiveConstants.FORMTYPE_ARCHIVE);
		}
		return HtmlRestResult.html("archive/v1/platformManager");
	}
	
	@RequestMapping(value = "/provinceManager", method = RequestMethod.GET)
	public HtmlRestResult provinceManager(String referId) {
		String loanapplyNo=referId;
		ModelResult<LoanApplyEntity> modelResult = loanInfoService.getLoanapplyInfo(loanapplyNo);
		LoanApplyEntity loanInfo = modelResult.getModel();
		String bankName = loanInfo.getBankLoanName();
		String bankTypeId = ArchiveConstants.getBankTypeId(bankName);
		String loanId=loanInfo.getLoanId();
		if (StringUtils.isNotBlank(bankTypeId)) {
			List<FieldEntity> platformFields = archiveService.getFieldListByType(bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE);
			List<FieldEntity> provinceFields = new ArrayList<>();
			for (FieldEntity fieldEntity : platformFields) {
				provinceFields.add(fieldEntity.clone());
			}
			
			ArchiveRecordEntity platformRecord=getFieldValue(platformFields, loanapplyNo, bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE);
			ArchiveRecordEntity provinceRecord=getFieldValue(provinceFields, loanapplyNo, bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE_PROVINCE_CHECK);
			
			
			//判断是否保存
			if(provinceRecord!=null&&provinceFields!=null&&provinceFields.size()>0){
				ViewContext.put("isSave", "show");
			}else{
				ViewContext.put("isSave", "hidden");
			}
			
			ViewContext.put("platformFields", platformFields);
			ViewContext.put("provinceFields", provinceFields);
			ViewContext.put("platformRecord", platformRecord);
			ViewContext.put("provinceRecord", provinceRecord);
			ViewContext.put("bankTypeId", bankTypeId);
			ViewContext.put("loanapplyNo", loanapplyNo);
			ViewContext.put("formTypeId", ArchiveConstants.FORMTYPE_ARCHIVE_PROVINCE_CHECK);
			ViewContext.put("loanId", loanId);
		}
		return HtmlRestResult.html("archive/v1/provinceManager");
	}
	
	@RequestMapping(value = "/reviewHQ", method = RequestMethod.GET)
	public HtmlRestResult reviewHQ(String referId) {
		String loanapplyNo=referId;
		ModelResult<LoanApplyEntity> modelResult = loanInfoService.getLoanapplyInfo(loanapplyNo);
		LoanApplyEntity loanInfo = modelResult.getModel();
		String bankName = loanInfo.getBankLoanName();
		String loanId=loanInfo.getLoanId();
		String bankTypeId = ArchiveConstants.getBankTypeId(bankName);
		if (StringUtils.isNotBlank(bankTypeId)) {
			List<FieldEntity> archiveFields = archiveService.getFieldListByType(bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE);
			ArchiveRecordEntity archiveRecord=getFieldValue(archiveFields, loanapplyNo, bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE_HQ_CHECK);
			if (archiveRecord == null ) {
				archiveRecord = getFieldValue(archiveFields, loanapplyNo, bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE_PROVINCE_CHECK);
			}
			ViewContext.put("archiveFields", archiveFields);
			ViewContext.put("archiveRecord", archiveRecord);
			ViewContext.put("bankTypeId", bankTypeId);
			ViewContext.put("loanapplyNo", loanapplyNo);
			ViewContext.put("formTypeId", ArchiveConstants.FORMTYPE_ARCHIVE_HQ_CHECK);
			ViewContext.put("loanId", loanId);
		}
		return HtmlRestResult.html("archive/v1/reviewHQ");
	}
	
	@RequestMapping(value = "/archiveHQ", method = RequestMethod.GET)
	public HtmlRestResult archiveHQ(String referId) {
		buildData(referId,null);
		ViewContext.put("showSaveBtn", true);
		return HtmlRestResult.html("archive/v1/archiveHQ");
	}
	
	@RequestMapping(value = "/archiveHQPopup", method = RequestMethod.GET)
	public HtmlRestResult archiveHQPopup(String referId) {
		buildData(referId,null);
		return HtmlRestResult.popHtmlFragment("archive/v1/archiveHQ");
	}
	
	@RequestMapping("/fileDiv")
	public HtmlRestResult getFileDiv(String loanapplyNo,String loanId,String datalistType,String hidenBtn){
		ViewContext.put("loanapplyNo", loanapplyNo);
		ViewContext.put("loanId", loanId);
		/**** 查询附件 ****/
		List<O2oDataListEntity> o2oDataList = o2oDataListService.findByEntityList(loanapplyNo);
		ViewContext.put("o2oDataList", o2oDataList);
		ViewContext.put("datalistType", datalistType);
		if(hidenBtn == null){
			hidenBtn="false";
		}
		ViewContext.put("hidenBtn", hidenBtn);
		return HtmlRestResult.html("archive/v1/uploadDiv");
	}
	
	public void buildData(String referCode){
		ModelResult<LoanApplyEntity> modelResult = loanInfoService.getLoanapplyInfo(null, referCode);
		LoanApplyEntity loanInfo = modelResult.getModel();
		buildData(loanInfo,null);
	}
	
	public void buildData(String referId,String bid){
		String loanapplyNo=referId;
		ModelResult<LoanApplyEntity> modelResult = loanInfoService.getLoanapplyInfo(loanapplyNo);
		LoanApplyEntity loanInfo = modelResult.getModel();
		buildData(loanInfo,bid);
		
	}
	
	public void buildData(LoanApplyEntity loanInfo,String bid){
		String loanapplyNo=loanInfo.getLoanapplyNo();
		String bankName = loanInfo.getBankLoanName();
		String bankTypeId = ArchiveConstants.getBankTypeId(bankName);
		if (StringUtils.isNotBlank(bankTypeId)) {
			List<FieldEntity> bankFields = archiveService.getFieldListByType(bankTypeId, ArchiveConstants.FORMTYPE_BANK);
			List<FieldEntity> financeFields = archiveService.getFieldListByType(bankTypeId, ArchiveConstants.FORMTYPE_FINANCE);
			List<FieldEntity> archiveFields = archiveService.getFieldListByType(bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE_INFO);
			getFieldValue(bankFields, loanapplyNo, bankTypeId, ArchiveConstants.FORMTYPE_BANK);
			ArchiveRecordEntity archiveRecord=null;
			if(StringUtils.isNotBlank(bid)){
				ArchiveBorrowEntity model = archiveBorrowService.queryArchiveBorrowById(bid);
				if (model != null) {
					convertJson(model.getCw_contentJson(),financeFields);
					convertJson(model.getCk_contentJson(),archiveFields);
					archiveRecord =archiveRecordService.queryArchiveRecord(loanapplyNo, bankTypeId,ArchiveConstants.FORMTYPE_ARCHIVE_INFO).getModel();
				}
				ViewContext.put("archiveBorrow", model);
			}else{
				getFieldValue(financeFields, loanapplyNo, bankTypeId, ArchiveConstants.FORMTYPE_FINANCE);
				archiveRecord=getFieldValue(archiveFields, loanapplyNo, bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE_INFO);
				CompensatoryDataEnter compensatory=o2oDCLoanService.findByBillCode(loanInfo.getBillCode());
				ViewContext.put("archiveBorrow", convertBorrowEntity(compensatory));
			}
			ViewContext.put("archiveRecord", archiveRecord);
			ViewContext.put("bankFields", bankFields);
			ViewContext.put("financeFields", financeFields);
			ViewContext.put("archiveFields", archiveFields);
			ViewContext.put("bankTypeId", bankTypeId);
			ViewContext.put("FORMTYPE_BANK", ArchiveConstants.FORMTYPE_BANK);
			ViewContext.put("FORMTYPE_FINANCE", ArchiveConstants.FORMTYPE_FINANCE);
			ViewContext.put("FORMTYPE_ARCHIVE_INFO", ArchiveConstants.FORMTYPE_ARCHIVE_INFO);
		}
		ViewContext.put("loanapplyNo", loanapplyNo);
	}
	
	

	public ArchiveRecordEntity getFieldValue(List<FieldEntity> fields, String loanapplyNo, String bankTypeId, String fromTypeId) {
		ModelResult<ArchiveRecordEntity> modelResult = archiveRecordService.queryArchiveRecord(loanapplyNo, bankTypeId,fromTypeId);
		ArchiveRecordEntity model = modelResult.getModel();
		if (model != null) {
			convertJson(model.getContentJson(),fields);
		}
		return model;
	}
	
	private void convertJson(String json,List<FieldEntity> fields){
		JSONObject obj = JSONObject.parseObject(json);
		for (FieldEntity f : fields) {
			String fieldValue = obj.getString(f.getFieldName()+FieldEntity.CK);
			if(StringUtils.isBlank(fieldValue))
				fieldValue = obj.getString(f.getFieldName()) == null ? "0" : obj.getString(f.getFieldName());
			f.setFieldValue(fieldValue);
			
			String beLeft = obj.getString(f.getFieldName()+FieldEntity.SY);
			if(StringUtils.isBlank(beLeft))
				beLeft = fieldValue;
			f.setBeLeft(beLeft);
			
			String lend = obj.getString(f.getFieldName()+FieldEntity.JY);
			if(StringUtils.isBlank(lend))
				lend = "0";
			f.setLend(lend);
		}
	}

	@RequestMapping(value = "/saveArchiveRecord", method = RequestMethod.POST)
	public BaseRestResult<String> saveArchiveRecord(ArchiveRecordEntity entity){
		return save(entity);
	}
	
	@RequestMapping(value = "/saveArchiveRecords", method = RequestMethod.POST)
	@Transactional(transactionManager = "o2oTransactionManager")
	public BaseRestResult<String> saveArchiveRecords(String archiveRecordJSON){
		try {
			if (StringUtils.isBlank(archiveRecordJSON)) {
				return BaseRestResult.warn("参数不能为空");
			}
			JSONObject obj=JSONObject.parseObject(archiveRecordJSON);
			ArchiveRecordEntity bank=obj.getObject(ArchiveConstants.FORMTYPE_BANK, ArchiveRecordEntity.class);
			ArchiveRecordEntity finance=obj.getObject(ArchiveConstants.FORMTYPE_FINANCE, ArchiveRecordEntity.class);
			ArchiveRecordEntity archiveInfo=obj.getObject(ArchiveConstants.FORMTYPE_ARCHIVE_INFO, ArchiveRecordEntity.class);
			save(bank);
			save(finance);
			save(archiveInfo);
			return BaseRestResult.info("保存成功").buildClosestReloadResult();
		} catch (Exception e) {
			logger.info(e.getMessage()+","+e.getStackTrace());
		}
		return BaseRestResult.warn("保存失败，请联系管理员");
	}
	
	private BaseRestResult<String> save(ArchiveRecordEntity entity){
		User user = UserHolder.getUser();
		ModelResult<ArchiveRecordEntity> modelResult =archiveRecordService.queryArchiveRecord(entity.getLoanapplyNo(), entity.getBankTypeId(), entity.getFormTypeId());
		ArchiveRecordEntity model=modelResult.getModel();
		entity.setUpdator(user.getAccount());
		if (model == null) {
			if(StringUtils.equals(ArchiveConstants.FORMTYPE_ARCHIVE_INFO, entity.getFormTypeId())){
				//生成柜号、编号
				ProvincePlatformEntity provincePlatformEntity=archiveRecordDao.queryProvinceInfoByLoanId(entity.getLoanapplyNo());
				Map<String,String> map=archiveConstants.getCabinetCode("GD", provincePlatformEntity.getRegional_name(), 6);
				entity.setArchiveNo(map.get("cabinetCode"));
				entity.setCabinetNo(map.get("cabinetNo"));
			}
			entity.setCreator(user.getAccount());
			ModelResult<Boolean> saveResult =archiveRecordService.insertArchiveRecord(entity);
			Boolean result=saveResult.getModel();
			if(result){
				return BaseRestResult.info("保存成功");
			}
		}else{
			entity.setArchiveNo(model.getArchiveNo());
			entity.setCabinetNo(model.getCabinetNo());
			ModelResult<Boolean> updateResult =archiveRecordService.updateArchiveRecord(entity);
			Boolean result=updateResult.getModel();
			if(result){
				return BaseRestResult.info("保存成功");
			}
		}
		return BaseRestResult.warn("保存失败，请联系管理员");
	}
	
	@RequestMapping(value = "/startArchive", method = RequestMethod.GET)
	public BaseRestResult<String> startArchive(String loanapplyNo){
		try {
			if (StringUtils.isBlank(loanapplyNo)) {
				return BaseRestResult.info("贷款no不能为空!");
			}
			O2oLoanapplyEntity loan = o2oLoanapplyService.findById(loanapplyNo);
			String isConfig = ArchiveConstants.getBankTypeId(loan.getBankLoanName());
			if (StringUtils.isBlank(isConfig)) {
				PubDditem pubDditem = pubDditemService.queryPubDditem("10340",loan.getBankLoanName());
				return BaseRestResult.info("目前暂不支持"+pubDditem.getItemName()+"银行贷后归档，开始归档时间请留意总部通知");
			}
			com.eascs.workflow.common.vo.ModelResult<Boolean> modelResult= archiveTask.startUp(loanapplyNo);
			if (modelResult.isSuccess()) {
				return BaseRestResult.info("档案归档发起成功").andRefresh();
			}
			return BaseRestResult.warn("档案归档发起失败,"+modelResult.getErrMsg());
		} catch (Exception e) {
			return BaseRestResult.warn("档案归档发起失败，请联系管理员");
		}
		
	}
	
	
	/*
	 * 归档打印
	 * param:贷款id，归档id
	 */

	@RequestMapping("/print")
	public BaseRestResult<String> print(String type,String loanapplyNo,String bankTypeId){
		O2oLoanapplyEntity loanapply = o2oLoanapplyService.findContinueById(loanapplyNo);
		ViewContext.put("loanapply", loanapply);
		ViewContext.put("bankTypeId", bankTypeId);
		ViewContext.put("loanapplyNo", loanapplyNo);
		ViewContext.put("formTypeId", ArchiveConstants.FORMTYPE_ARCHIVE);
		ViewContext.put("type", type);
		ViewContext.put("loanId", loanapply.getLoanId());
		
		if(("plat").equals(type)||("platOld").equals(type)){
			List<FieldEntity> archiveFields = archiveService.getFieldListByType(bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE);
			ArchiveRecordEntity archiveRecord=getFieldValue(archiveFields, loanapplyNo, bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE);
			ViewContext.put("archiveFields", archiveFields);
			ViewContext.put("archiveRecord", archiveRecord);
			if(("platOld").equals(type)){
				return HtmlRestResult.popHtmlFragment("archive/v1/platPrintOld");
			}
			return HtmlRestResult.popHtmlFragment("archive/v1/platPrint");
		}else{
			List<FieldEntity> platformFields = archiveService.getFieldListByType(bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE);
			List<FieldEntity> provinceFields = new ArrayList<>();
			for (FieldEntity fieldEntity : platformFields) {
				provinceFields.add(fieldEntity.clone());
			}
			ArchiveRecordEntity provinceRecord=getFieldValue(provinceFields, loanapplyNo, bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE_PROVINCE_CHECK);
			ViewContext.put("provinceRecord", provinceRecord);
			ViewContext.put("provinceFields", provinceFields);
			return HtmlRestResult.popHtmlFragment("archive/v1/provincePrint");
		}
	}
	/**
	 * ------------------------------二次归档------------------------------------------------------
	 * */
	@RequestMapping(value = "/saveRepeatArchiveRecord", method = RequestMethod.POST)
	public BaseRestResult<String> saveRepeatArchiveRecord(ArchiveRecordRepeatEntity param,String billCode){
		LoanApplyEntity loanInfo = loanInfoService.getLoanapplyInfo(null, billCode).getModel();
		if(!StringUtils.equals(loanInfo.getIsPlaceOnFile(), "CLO")){
			return BaseRestResult.warn("归档未完成，不能进行补充归档!");
		}
		
		ArchiveRecordRepeatEntity entity =null;
		if(StringUtils.isNotBlank(param.getId()))
			entity = archiveRecordDao.queryArchiveRepeatRecordById(param.getId());
		User user = UserHolder.getUser();
		if( entity == null ){
			ModelResult<ArchiveRecordEntity> modelResult =archiveRecordService.queryArchiveRecord(param.getLoanapplyNo(), param.getBankTypeId(), ArchiveConstants.FORMTYPE_ARCHIVE_INFO);
			ArchiveRecordEntity model=modelResult.getModel();
			entity = new ArchiveRecordRepeatEntity();
			BeanUtils.copyProperties(param, entity);
			
			String bill = com.eascs.admin.common.utils.StringUtils.getFourBitYearMonth(new Date());
			String prefix = "GD2-" + bill;
			String bcode = sequenceService.getSeq("GD2", 5, prefix);
			entity.setGdCode(bcode);
			entity.setArchiveNo(model.getArchiveNo());
			entity.setCabinetNo(model.getCabinetNo());
			entity.setUpdator(user.getAccount());
			entity.setCreator(user.getAccount());
			entity.setWfState(-1);
			archiveRecordDao.insertArchiveRepeatRecord(entity);
		}else{
			param.setUpdator(user.getAccount());
			archiveRecordDao.updateArchiveRepeatRecord(param);
		}
		return BaseRestResult.info("保存成功").andRedirect("/archive/v1/repeatGdNewDes?gdId=" + entity.getId() + "&billCode=" + billCode+"&formTypeId="+param.getFormTypeId());
		//return BaseRestResult.info("保存成功").andRedirect("/archive/v1/repeatGdList?billCode=" + billCode);
	}
	
	
	@RequestMapping(value = "/deleteRepeatArchiveRecord")
	public BaseRestResult<String> deleteRepeatArchiveRecord(String gdId,String billCode){
		archiveRecordDao.deleteArchiveRepeatRecord(gdId);
		//return BaseRestResult.info("删除成功").andRefresh();
		return BaseRestResult.info("删除成功").andRedirect("/archive/v1/repeatGdList?billCode=" + billCode);
	}
	
	@RequestMapping(value = "/gdRepeatStart", method = RequestMethod.GET)
	public BaseRestResult<String> gdRepeatStart(String gdId,String billCode){
		if (StringUtils.isBlank(gdId)) {
			return BaseRestResult.warn("参数不能为空");
		}
		ArchiveRecordRepeatEntity entity = archiveRecordDao.queryArchiveRepeatRecordById(gdId);
		com.eascs.workflow.common.vo.ModelResult<Boolean> modelResult=gd2StartUp(entity.getLoanapplyNo(),gdId,entity.getGdCode());
		if(!modelResult.getModel() || !modelResult.isSuccess()){
			logger.info("启动补充归档流程失败msg:[{}]", modelResult.getErrMsg());
			return BaseRestResult.warn("启动补充归档流程失败"+modelResult.getErrMsg()).andRefresh();
		}
		//return BaseRestResult.info("启动补充归档流程成功").andRefresh();
		return BaseRestResult.info("启动补充归档流程成功").andRedirect("/archive/v1/repeatGdList?billCode=" + billCode);
	}
	
	//二次归档流程启动
	public com.eascs.workflow.common.vo.ModelResult<Boolean> gd2StartUp(String loanapplyNo,String gdId,String gdCode) {
		try {
			O2oLoanapplyEntity loan = o2oLoanapplyService.findById(loanapplyNo);
			WFRequestParam param = new WFRequestParam();
			param.setReferId(gdId);
			param.setReferCode(gdCode);
			param.setReferUrl(serviceUrl + "archive/rest/v1/gd2ApprovalPopup?loanapplyNo=" + loanapplyNo );
			// 本地调试代码
			//param.setReferUrl("http://127.0.0.1:8090/archive/rest/v1/gd2ApprovalPopup?loanapplyNo=" + loanapplyNo );
			// 本地调试代码
			param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
			param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_BC_ARCHIVE));
			param.setProcessVersion("v1");
			param.setAppliedby(loan.getOperatorNo());
			param.setAppliedbyName(loan.getOperatorName());
			param.setOrgNo(loan.getLtd());
			//摘要
			StringBuffer appliedDes = new StringBuffer("借款人:");
			appliedDes.append(o2oLoanapplyService.findLoanUserEntity(loan.getLoanapplyNo(),loan.getLoanId()).getUserFullName());
			appliedDes.append("，放款金额:");
			java.text.DecimalFormat df         =new java.text.DecimalFormat("0.00"); //格式化，保留两位小数
			BigDecimal loanAmount=new BigDecimal(0);
			if ("EA".equals(loan.getLoanType())||"FQ".equals(loan.getLoanType())) {
				loanAmount = service.findDataByBillCode(loan.getBillCode()).getLoanAmount();
			}else{
				loanAmount = o2oLoanService.queryBillCode(loan.getBillCode()).getLoanAmount();
			}
			appliedDes.append(df.format(loanAmount));
			param.setAppliedDes(appliedDes.toString());
			logger.info("启动补充归档，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】", loan.getLoanapplyNo(), loan.getBillCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), loan.getLtd());
			com.eascs.workflow.common.vo.ModelResult<Boolean> modelResult = workFlowService.instance(param);
			if (modelResult.isSuccess()) {
				archiveRecordDao.updateArchiveRepeatState(gdId, ProcessTaskMain.PROECESS_STATUS_HANDING);
			} else {
				logger.error("启动补充归档失败，贷款单号为：【{}】，错误信息{}", loanapplyNo, modelResult.getErrMsg());
			}
			return modelResult;
		} catch (Exception e) {
			logger.error("补充归档失败，贷款单号为：【{}】，错误：{}，", loanapplyNo, e.getMessage());
			return new com.eascs.workflow.common.vo.ModelResult<Boolean>("GD Repeat ERROR", "补充归档失败");
		}
	}
	
	
	@RequestMapping(value = "/gd2ApprovalPopup", method = RequestMethod.GET)
	public HtmlRestResult gd2ApprovalPopup(String loanapplyNo, String nodeAuditorId, String approvalStatus,String referId) {
		O2oLoanapplyEntity loanapply = o2oLoanapplyService.findContinueById(loanapplyNo);
		String approvalUrl = baseUtils.getApprovalUrl(nodeAuditorId, ProcessTemplate.SYSTEM_MODULE_O2O);// 审批代办列表详情URL
		approvalUrl += "&loadServiceUrl="+serviceHomeUrl+"/work/jqUpload";
		String agreeUrl = baseUtils.getApprovalAgreeUrl(loanapplyNo, nodeAuditorId, ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("approvalUrl", approvalUrl);
		ViewContext.put("approvalStatus", approvalStatus);// 流程经办状态是待办/已办/已发起，待办状态才显示审批栏
		String isNotContinue=null;
		O2oLoanapplyEntity loanapplyEntity=loanDetailService.queryLoanapplyBillCode(loanapply.getLoanapplyNo(), loanapply.getLoanId(), loanapply.getBillCode(),loanapply.getCreateDate());
		if(loanapplyEntity!=null){
			loanapply.setContinueLoanParenNo(loanapplyEntity.getBillCode());
			isNotContinue="Y";
		}
		ViewContext.put("isNotContinue", isNotContinue);
		ViewContext.put("loanapply", loanapply);
		O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loanapply.getLoanId(), loanapply.getLoanapplyNo());
		ViewContext.put("loanUser", loanUser);
		ViewContext.put("domain", domain);
		return HtmlRestResult.popHtmlFragment("/archive/v1/repeatGd/repeatGdApprovalPopup");
	}
	
	
	@RequestMapping(value = "/gd2DynamicForm", method = RequestMethod.GET)
	public HtmlRestResult gd2DynamicForm(String referId,String nodeCode) {
		ArchiveRecordRepeatEntity entity = archiveRecordDao.queryArchiveRepeatRecordById(referId);
		if(StringUtils.isNotBlank(entity.getContentJson())){
			List<FieldEntity> fields=archiveService.getFieldListAll();
			JSONObject obj = JSONObject.parseObject(entity.getContentJson());
			Iterator<FieldEntity> iterator=fields.iterator();
			while(iterator.hasNext()){
				FieldEntity f=iterator.next();
				String fieldValue = obj.getString(f.getFieldName());
				if(StringUtils.isBlank(fieldValue))
					iterator.remove();
				else	
					f.setFieldValue(fieldValue);
			}
			if(fields.size() > 0)
				ViewContext.put("fields", fields);
		}
		
		if(StringUtils.isNotBlank(entity.getCwContentJson())){
			List<FieldEntity> cwfields=archiveService.getFieldListAll();
			JSONObject obj2 = JSONObject.parseObject(entity.getCwContentJson());
			Iterator<FieldEntity> iterator2=cwfields.iterator();
			while(iterator2.hasNext()){
				FieldEntity f=iterator2.next();
				String fieldValue = obj2.getString(f.getFieldName());
				if(StringUtils.isBlank(fieldValue))
					iterator2.remove();
				else	
					f.setFieldValue(fieldValue);
			}
			if(cwfields.size() > 0)
				ViewContext.put("cwfields", cwfields);
		}
		User user = UserHolder.getUser();
		ViewContext.put("currentUser", user);
		ViewContext.put("nodeCode", nodeCode);
		ViewContext.put("referId", referId);
		ViewContext.put("gdRepeatEntity", entity);
		ViewContext.put("hidenBtn", "false");
		if(!StringUtils.equals(nodeCode, "GD2_PTFXJL")){
			ViewContext.put("hidenBtn", "true");
		}
		if(StringUtils.equals(nodeCode, "GD2_SYFXJL")){
			return HtmlRestResult.html("/archive/v1/repeatGd/dynamicForm2");
		}
		return HtmlRestResult.html("/archive/v1/repeatGd/dynamicForm");
	}
	
	@RequestMapping(value = "/saveSendGDRepeatInfo", method = RequestMethod.GET)
	public BaseRestResult<String> saveSendGDRepeatInfo(ArchiveRecordRepeatEntity entity ){
		if (entity == null) {
			return BaseRestResult.warn("参数不能为空");
		}
		archiveRecordDao.saveSendArchiveRepeatInfo(entity);
		return BaseRestResult.info("保存成功");
	}
	
	@RequestMapping(value = "/savePtSendArchiveRepeatInfo", method = RequestMethod.GET)
	public BaseRestResult<String> savePtSendArchiveRepeatInfo(ArchiveRecordRepeatEntity entity ){
		if (entity == null) {
			return BaseRestResult.warn("参数不能为空");
		}
		archiveRecordDao.savePtSendArchiveRepeatInfo(entity);
		return BaseRestResult.info("保存成功");
	}
	/**
	 * ------------------------------借阅------------------------------------------------------
	 * */
	
	@RequestMapping(value = "/borrowPopup", method = RequestMethod.GET)
	public HtmlRestResult borrowPopup(String referId,@RequestParam(value = "bid", required = false)String bid) {
		buildData(referId,bid);
		User user = UserHolder.getUser();
		ViewContext.put("currentUser", user);
		ViewContext.put("borrowPopup", true);
		ViewContext.put("bid", bid);
		return HtmlRestResult.popHtmlFragment("archive/v1/borrowPopup");
	}
	
	@RequestMapping(value = "/borrowDynamicForm", method = RequestMethod.GET)
	public HtmlRestResult borrowDynamicForm(String referId,String nodeCode) {
		ArchiveBorrowEntity borrow=archiveBorrowService.queryArchiveBorrowById(referId);
		buildData(borrow.getLoanapply_no(),borrow.getBid());
		User user = UserHolder.getUser();
		ViewContext.put("currentUser", user);
		ViewContext.put("borrowPopup", true);
		ViewContext.put("bid", borrow.getBid());
		ViewContext.put("nodeCode", nodeCode);
		ViewContext.put("referId", referId);
		ViewContext.put("archiveBorrow", borrow);
		ViewContext.put("hidenBtn", "false");
		if(!StringUtils.equals(nodeCode, "JY_DAJC")){
			ViewContext.put("hidenBtn", "true");
		}
		return HtmlRestResult.html("archive/v1/borrowDynamicForm");
	}
	
	@RequestMapping(value = "/ajaxBorrowRecord", method = RequestMethod.GET)
	public HtmlRestResult ajaxBorrowRecord(String referId,int pageSize,int pageIndex) {
		if (pageSize == 0) 
			pageSize=15;
		ArchiveBorrowEntity archiveBorrowEntity=new ArchiveBorrowEntity();
		archiveBorrowEntity.setLoanapply_no(referId);
		ModelResult<PageResult<Object[]>> modelResult=archiveBorrowService.queryListPage(archiveBorrowEntity, pageSize, pageIndex);
		if (modelResult.isSuccess()) {
			PageResult<Object[]> pageResult= modelResult.getModel();
			String[] titles = { "单据号", "申请时间", "申请人", "预计归还时间", "实际归还时间", "状态"};
			SelectDataOption[] selectDataOptions = { null, null, null, null, null,new SelectDataOption("GD_JY")};
			PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, "/archive/v1/queryList?pageIndex=");
			Button updateBtn = new AjaxButton("编辑", "/archive/rest/v1/borrowPopup?referId="+referId+"&bid=");
			Button delBtn = new AjaxButton("删除", "/archive/rest/v1/deleteArchiveBorrow?bid=");
			Button startBtn = new AjaxButton("启动借阅流程", "/archive/rest/v1/borrowStart?bid=");
			User user = UserHolder.getUser();
			updateBtn.setShowButtonFilter(new ShowButtonFilter() {
				@Override
				public boolean filter(Object param) {
					Object[] params = (Object[]) param;
					if(!StringUtils.equals(user.getCname(), params[3]+"") || !StringUtils.equals(user.getCname(), "鲁俊")){
						return false;
					}
					if(!StringUtils.equals("NEW", params[6]+"")){
						return false;
					}
					return true;
				}
			});
			delBtn.setShowButtonFilter(new ShowButtonFilter() {
				@Override
				public boolean filter(Object param) {
					Object[] params = (Object[]) param;
					if(!StringUtils.equals(user.getCname(), params[3]+"") || !StringUtils.equals(user.getCname(), "鲁俊")){
						return false;
					}
					if(!StringUtils.equals("NEW", params[6]+"")){
						return false;
					}
					return true;
				}
			});
			startBtn.setShowButtonFilter(new ShowButtonFilter() {
				@Override
				public boolean filter(Object param) {
					Object[] params = (Object[]) param;
					if(!StringUtils.equals(user.getCname(), params[3]+"") || !StringUtils.equals(user.getCname(), "鲁俊")){
						return false;
					}
					if(!StringUtils.equals("NEW", params[6]+"")){
						return false;
					}
					return true;
				}
			});
				
			
			Button[] btns = new Button[] { updateBtn ,delBtn,startBtn};
			Button tBtn = ButtonHelper.createOpenButton(null, "/archive/v1/borrowApprovalDes?bid=");
			Button[] titleButtons = new Button[]{tBtn};
			paginationInfo.setTitleButtons(titleButtons);
			paginationInfo.setBuildPagingNavigation(true);
			paginationInfo.setFirstRenderColumnIndex(1);
			paginationInfo.setMoreButtons(btns);
			paginationInfo.setSelectDataOptions(selectDataOptions);
			ViewContext.put("paginationInfo", paginationInfo);
			ViewContext.put("loanapplyNo", referId);
		}
		return HtmlRestResult.html("archive/v1/borrowList");
	}
	
	
	@RequestMapping(value = "/deleteArchiveBorrow", method = RequestMethod.GET)
	@Transactional(transactionManager = "o2oTransactionManager")
	public BaseRestResult<String> deleteArchiveBorrow(String bid){
		if (StringUtils.isBlank(bid)) {
			return BaseRestResult.warn("参数不能为空");
		}
		try {
			int result=archiveBorrowService.deleteArchiveBorrowById(bid);
			if (result == 0) {
				logger.info("归档借阅删除数据失败msg:[{}],参数:[{}]", "o2o_archive_borrow表删除数据出错",bid);
				throw new RuntimeException();
			}
			//统计剩余份数
			ArchiveBorrowEntity entity =archiveBorrowService.queryArchiveBorrowById(bid);
			if(entity == null){
				logger.info("归档借阅删除数据失败msg:[{}],参数:[{}]", "o2o_archive_borrow表未找到借阅数据",bid);
				throw new RuntimeException();
			}
			caclArchiveRecord(entity,false);
			//代偿数据处理 
			saveDCInfo(null,entity,entity.getLoanapply_no());
			return BaseRestResult.info("删除成功").andRefresh();
		} catch (Exception e) {
			logger.info("归档借阅删除数据失败msg:[{}],statck:[{}]", e.getMessage(),e.getStackTrace());
			throw new RuntimeException();
		}
	}
	
	
	
	@RequestMapping(value = "/saveSendBorrowInfo", method = RequestMethod.GET)
	public BaseRestResult<String> saveSendBorrowInfo(ArchiveBorrowEntity entity ){
		if (entity == null) {
			return BaseRestResult.warn("参数不能为空");
		}
		archiveBorrowService.saveSendBorrowInfo(entity);
		return BaseRestResult.info("保存成功");
	}
	
	
	@RequestMapping(value = "/borrowStart", method = RequestMethod.GET)
	public BaseRestResult<String> borrowStart(String bid){
		if (StringUtils.isBlank(bid)) {
			return BaseRestResult.warn("参数不能为空");
		}
		ArchiveBorrowEntity entity=archiveBorrowService.queryArchiveBorrowById(bid);
		com.eascs.workflow.common.vo.ModelResult<Boolean> modelResult=jqStartUp(entity.getLoanapply_no(),entity);
		if(!modelResult.getModel() || !modelResult.isSuccess()){
			logger.info("启动借阅流程失败msg:[{}]", modelResult.getErrMsg());
			return BaseRestResult.warn("启动借阅流程失败"+modelResult.getErrMsg()).andRefresh();
		}
		return BaseRestResult.info("启动借阅流程成功").andRefresh();
	}
	
	
	@RequestMapping(value = "/saveArchiveBorrowRecords", method = RequestMethod.POST)
	@Transactional(transactionManager = "o2oTransactionManager")
	public BaseRestResult<String> saveArchiveBorrowRecords(ArchiveBorrowEntity entity){
		if (entity == null) {
			return BaseRestResult.warn("参数不能为空");
		}
		try {
			if(StringUtils.isBlank(entity.getBid())){
				String bill = com.eascs.admin.common.utils.StringUtils.getFourBitYearMonth(new Date());
				String prefix = "JY-" + bill;
				String bcode = sequenceService.getSeq("JY", 5, prefix);
				entity.setBcode(bcode);
				User user = UserHolder.getUser();
				entity.setProposer_no(user.getNo());
				entity.setProposer(user.getCname());
				int result=archiveBorrowService.saveArchiveBorrowRecord(entity);
				if (result == 0) {
					logger.info("归档借阅新增数据失败msg:[{}],参数:[{}]", "o2o_archive_borrow表插入数据出错",entity.toString());
					throw new RuntimeException();
				}
				//代偿数据处理 
				saveDCInfo(entity,null);
				//统计剩余份数
				caclArchiveRecord(entity,true);
				//启动借阅流程
				if (StringUtils.isNotBlank(entity.getBid()) && StringUtils.isNotBlank(entity.getLoanapply_no())) {
					com.eascs.workflow.common.vo.ModelResult<Boolean> modelResult=jqStartUp(entity.getLoanapply_no(),entity);
					if(!modelResult.getModel() || !modelResult.isSuccess()){
						logger.info("启动借阅流程失败msg:[{}]", modelResult.getErrMsg());
						throw new RuntimeException();
					}
				}
			}else{
				ArchiveBorrowEntity ab=archiveBorrowService.queryArchiveBorrowById(entity.getBid());
				//统计剩余份数
				caclArchiveRecord(ab,false);//修改部分，先归还、再借阅 
				caclArchiveRecord(entity,true);
				//代偿数据处理 
				saveDCInfo(entity,ab);
				//修改借阅记录
				ab.setBorrowDes(entity.getBorrowDes());
				ab.setPre_return_time(entity.getPre_return_time());
				ab.setCk_contentJson(entity.getCk_contentJson());
				ab.setCw_contentJson(entity.getCw_contentJson());
				ab.setDc_ems_jy(entity.getDc_ems_jy());
				ab.setDc_receipt_jy(entity.getDc_receipt_jy());
				ab.setDc_refund_jy(entity.getDc_refund_jy());
				ab.setDc_trans_jy(entity.getDc_trans_jy());
				int result=archiveBorrowService.updateArchiveBorrowRecordById(ab);
				if (result == 0) {
					logger.info("归档借阅修改数据失败msg:[{}],参数:[{}]", "o2o_archive_borrow表插入数据出错",entity.toString());
					throw new RuntimeException();
				}
			}
			return BaseRestResult.info("保存成功").andRefresh();
		} catch (Exception e) {
			logger.info("归档借阅保存数据失败msg:[{}],statck:[{}]", e.getMessage(),e.getStackTrace());
			throw new RuntimeException();
		}
	}
	
	
	/**
	 * param caclWay 计算方式 :true 借阅，false  归还 
	 * 
	 * */
	public void caclArchiveRecord(ArchiveBorrowEntity entity,boolean caclWay){
		String loanapplyNo=entity.getLoanapply_no();
		ModelResult<LoanApplyEntity> modelResult = loanInfoService.getLoanapplyInfo(loanapplyNo);
		LoanApplyEntity loanInfo = modelResult.getModel();
		String bankName = loanInfo.getBankLoanName();
		String bankTypeId = ArchiveConstants.getBankTypeId(bankName);
		if (StringUtils.isNotBlank(bankTypeId)) {
			ModelResult<ArchiveRecordEntity> financeModelResult=archiveRecordService.queryArchiveRecord(loanapplyNo,bankTypeId, ArchiveConstants.FORMTYPE_FINANCE);
			ModelResult<ArchiveRecordEntity> archiveModelResult=archiveRecordService.queryArchiveRecord(loanapplyNo,bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE_INFO);
			
			List<FieldEntity> financeFields = archiveService.getFieldListByType(bankTypeId, ArchiveConstants.FORMTYPE_FINANCE);
			List<FieldEntity> archiveFields = archiveService.getFieldListByType(bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE_INFO);
			ArchiveRecordEntity  financeModel=financeModelResult.getModel();
			ArchiveRecordEntity  archiveModel=archiveModelResult.getModel();
			
			String financeContentJson=buildRecordJson(entity.getCw_contentJson(),financeModel.getContentJson(),financeFields,caclWay);
			String archiveContentJson=buildRecordJson(entity.getCk_contentJson(),archiveModel.getContentJson(),archiveFields,caclWay);
			
			int result1=archiveRecordService.updateArchiveRecordContentJson(financeModel.getId(), financeContentJson);
			if (result1 == 0) {
				logger.info("setp1:归档借阅数据[财务行归档]计算失败msg:[o2o_archive_record表修改数据出错],参数:[{}],[{}]", financeModel.getId(),financeContentJson);
				throw new RuntimeException();
			}
			int result2=archiveRecordService.updateArchiveRecordContentJson(archiveModel.getId(), archiveContentJson);
			if (result2 == 0) {
				logger.info("setp2:归档借阅数据[存柜资料]计算失败msg:[o2o_archive_record表修改数据出错],参数:[{}],[{}]", financeModel.getId(),archiveContentJson);
				throw new RuntimeException();
			}
			//修改所有借阅信息
			int result3=0;
			List<ArchiveBorrowEntity> list=archiveBorrowService.queryAllListByloanapplyNo(loanapplyNo);
			for (ArchiveBorrowEntity item : list) {
				String cw_contentJson=buildBorrwJson(item.getCw_contentJson(),financeContentJson,financeFields);
				String ck_contentJson=buildBorrwJson(item.getCk_contentJson(),archiveContentJson,archiveFields);
				item.setCw_contentJson(cw_contentJson);
				item.setCk_contentJson(ck_contentJson);
				result3 = archiveBorrowService.updateArchiveBorrow(item);
				if(StringUtils.isNoneBlank(entity.getBid()) && StringUtils.equals(entity.getBid(), item.getBid())){
					//修改操作处理，计算剩余数
					String cw_update=buildBorrwJson(entity.getCw_contentJson(),financeContentJson,financeFields);
					String ck_update=buildBorrwJson(entity.getCk_contentJson(),archiveContentJson,archiveFields);
					entity.setCk_contentJson(ck_update);
					entity.setCw_contentJson(cw_update);
				}
				if (result3 == 0) {
					logger.info("setp3:归档借阅数据计算失败msg:[o2o_archive_borrow表修改数据出错],参数:[{}]",item.toString());
					throw new RuntimeException();
				}
			}
		}
	}
	
	/**
	 * 生成存柜contentJson
	 * 
	 * param json  待借阅对象
	 * param recordJson   已存柜对象 
	 * */
	private String buildRecordJson(String json,String recordJson,List<FieldEntity> fields,boolean caclWay){
		JSONObject lend = JSONObject.parseObject(json);
		JSONObject record = JSONObject.parseObject(recordJson);
		JSONObject result = JSONObject.parseObject("{}");
		
		for (FieldEntity f : fields) {
			String fieldName =f.getFieldName();//存柜key
			String syKey=fieldName +FieldEntity.SY;//剩余key
			String jyKey=fieldName +FieldEntity.JY;//借阅key
			String fieldVal=record.getString(fieldName);
			result.put(fieldName, fieldVal);
			
			String lend_jyVal=lend.getString(jyKey);
			if(StringUtils.isBlank(lend_jyVal))
				lend_jyVal="0";
			String rec_syVal =record.getString(syKey);
			if(StringUtils.isBlank(rec_syVal))
				rec_syVal = fieldVal;
			int syVal = 0;
			if(caclWay)
				syVal = Integer.parseInt(rec_syVal) - Integer.parseInt(lend_jyVal) ;//借阅
			else 
				syVal = Integer.parseInt(rec_syVal) + Integer.parseInt(lend_jyVal) ;//归还 
			result.put(syKey, syVal+"");
			
			String rec_jyVal=record.getString(jyKey);
			if(StringUtils.isBlank(rec_jyVal))
				rec_jyVal="0";
			int jyVal= 0;
			if(caclWay)
				jyVal= Integer.parseInt(rec_jyVal) + Integer.parseInt(lend_jyVal);
			else
				jyVal= Integer.parseInt(rec_jyVal) - Integer.parseInt(lend_jyVal);
			result.put(jyKey, jyVal+"");
		}
		return result.toJSONString();
	}
	
	/**
	 * 生成借阅contentJson
	 * 
	 * param json  借阅对象
	 * param recordJson   已存柜对象 
	 * */
	private String buildBorrwJson(String json,String recordJson,List<FieldEntity> fields){
		JSONObject content = JSONObject.parseObject(json);
		JSONObject record = JSONObject.parseObject(recordJson);
		
		for (FieldEntity f : fields) {
			String fieldName =f.getFieldName();//存柜key
			String syKey=fieldName +FieldEntity.SY;//剩余key
			
			String syVal=record.getString(syKey);
			content.put(syKey, syVal);
		}
		return content.toString();
	}
	
	
	//借阅流程启动
	public com.eascs.workflow.common.vo.ModelResult<Boolean> jqStartUp(String loanapplyNo,ArchiveBorrowEntity entity) {
		try {
			O2oLoanapplyEntity loan = o2oLoanapplyService.findById(loanapplyNo);
			WFRequestParam param = new WFRequestParam();
			param.setReferId(entity.getBid());
			param.setReferCode(entity.getBcode());
			param.setReferUrl(serviceUrl + "archive/rest/v1/borrowApprovalPopup?loanapplyNo=" + loanapplyNo );
			// 本地调试代码
			//param.setReferUrl("http://127.0.0.1:8090/archive/rest/v1/borrowApprovalPopup?loanapplyNo=" + loanapplyNo );
			// 本地调试代码
			param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
			param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_BORROW_ARCHIVE));
			param.setProcessVersion("v1");
			param.setAppliedby(loan.getOperatorNo());
			param.setAppliedbyName(loan.getOperatorName());
			param.setOrgNo(loan.getLtd());
			//摘要
			StringBuffer appliedDes = new StringBuffer("借款人:");
			appliedDes.append(o2oLoanapplyService.findLoanUserEntity(loan.getLoanapplyNo(),loan.getLoanId()).getUserFullName());
			appliedDes.append("，借阅人:" + UserHolder.getUser().getCname());
			param.setAppliedDes(appliedDes.toString());
			logger.info("启动归档借阅，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】", loan.getLoanapplyNo(), loan.getBillCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), loan.getLtd());
			com.eascs.workflow.common.vo.ModelResult<Boolean> modelResult = workFlowService.instance(param);
			if (modelResult.isSuccess()) {
				archiveBorrowService.updateBorrowState(entity.getBid(), StatusContexts.WFTYPE_STATUS_RUN);
			} else {
				logger.error("启动归档借阅失败，贷款单号为：【{}】，错误信息{}", loanapplyNo, modelResult.getErrMsg());
			}
			return modelResult;
		} catch (Exception e) {
			logger.error("归档借阅失败，贷款单号为：【{}】，错误：{}，", loanapplyNo, e.getMessage());
			return new com.eascs.workflow.common.vo.ModelResult<Boolean>("GD BORROW ERROR", "归档借阅失败");
		}
	}
	
	
	@RequestMapping(value = "/borrowApprovalPopup", method = RequestMethod.GET)
	public HtmlRestResult borrowApprovalPopup(String loanapplyNo, String nodeAuditorId, String approvalStatus,String referId) {
		O2oLoanapplyEntity loanapply = o2oLoanapplyService.findContinueById(loanapplyNo);
		String approvalUrl = baseUtils.getApprovalUrl(nodeAuditorId, ProcessTemplate.SYSTEM_MODULE_O2O);// 审批代办列表详情URL
		approvalUrl += "&loadServiceUrl="+serviceHomeUrl+"/work/jqUpload";
		String agreeUrl = baseUtils.getApprovalAgreeUrl(loanapplyNo, nodeAuditorId, ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("approvalUrl", approvalUrl);
		ViewContext.put("approvalStatus", approvalStatus);// 流程经办状态是待办/已办/已发起，待办状态才显示审批栏
		String isNotContinue=null;
		O2oLoanapplyEntity loanapplyEntity=loanDetailService.queryLoanapplyBillCode(loanapply.getLoanapplyNo(), loanapply.getLoanId(), loanapply.getBillCode(),loanapply.getCreateDate());
		if(loanapplyEntity!=null){
			loanapply.setContinueLoanParenNo(loanapplyEntity.getBillCode());
			isNotContinue="Y";
		}
		ViewContext.put("isNotContinue", isNotContinue);
		ViewContext.put("loanapply", loanapply);
		O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loanapply.getLoanId(), loanapply.getLoanapplyNo());
		ViewContext.put("loanUser", loanUser);
		ViewContext.put("domain", domain);
		return HtmlRestResult.popHtmlFragment("/archive/v1/borrowApprovalPopup");
	}
	
	
	private ArchiveBorrowEntity convertBorrowEntity(CompensatoryDataEnter vo ){
		ArchiveBorrowEntity model =new ArchiveBorrowEntity();
		if(vo != null){
			model.setDc_trans_ck(vo.getTransferInvitationNum());
			model.setDc_trans_sy(vo.getTransferInvitationResidueNum());
			model.setDc_trans_jy(vo.getTransferInvitationLoanNum());
			
			model.setDc_ems_ck(vo.getEnsBillNum());
			model.setDc_ems_sy(vo.getEnsBillResidueNum());
			model.setDc_ems_jy(vo.getEnsBillLoanNum());
			
			model.setDc_receipt_ck(vo.getReceiptNum());
			model.setDc_receipt_sy(vo.getReceiptResidueNum());
			model.setDc_receipt_jy(vo.getReceiptLoanNum());
			
			model.setDc_refund_ck(vo.getRefundDetailNum());
			model.setDc_refund_sy(vo.getRefundDetailResidueNum());
			model.setDc_refund_jy(vo.getRefundDetailLoanNum());
		}
		return model;
	}
	
	
	private void saveDCInfo(ArchiveBorrowEntity entity,ArchiveBorrowEntity borrorw){
		saveDCInfo(entity,borrorw,entity.getLoanapply_no());
	}
	
	/**
	 * entity: 待借阅对象
	 * borrorw： 已借阅对象
	 * */
	private void saveDCInfo(ArchiveBorrowEntity entity,ArchiveBorrowEntity borrorw,String loanapplyNo){
		ModelResult<LoanApplyEntity> modelResult = loanInfoService.getLoanapplyInfo(loanapplyNo);
		LoanApplyEntity loanInfo = modelResult.getModel();
		CompensatoryDataEnter comps=o2oDCLoanService.findByBillCode(loanInfo.getBillCode());
		if(comps != null){
			int ensBillLoanNum = comps.getEnsBillLoanNum(); //借出
			int ensBillResidueNum =comps.getEnsBillResidueNum();//剩余
			int receiptLoanNum = comps.getReceiptLoanNum();
			int receiptResidueNum = comps.getReceiptResidueNum();
			int refundDetailLoanNum = comps.getRefundDetailLoanNum();
			int refundDetailResidueNum = comps.getRefundDetailResidueNum();
			int transferInvitationLoanNum = comps.getTransferInvitationLoanNum();
			int transferInvitationResidueNum = comps.getTransferInvitationResidueNum();
			
			if( borrorw != null){//修改部分，先归还，再借阅 
				ensBillLoanNum -= borrorw.getDc_ems_jy();
				ensBillResidueNum += borrorw.getDc_ems_jy();
				
				receiptLoanNum -= borrorw.getDc_receipt_jy();
				receiptResidueNum += borrorw.getDc_receipt_jy();
				
				refundDetailLoanNum -= borrorw.getDc_refund_jy();
				refundDetailResidueNum += borrorw.getDc_refund_jy();
				
				transferInvitationLoanNum -= borrorw.getDc_trans_jy();
				transferInvitationResidueNum += borrorw.getDc_trans_jy();
			}
			if(entity != null){	//排除部分
				ensBillLoanNum += entity.getDc_ems_jy();
				ensBillResidueNum -= entity.getDc_ems_jy();
				
				receiptLoanNum += entity.getDc_receipt_jy();
				receiptResidueNum -= entity.getDc_receipt_jy();
				
				refundDetailLoanNum += entity.getDc_refund_jy();
				refundDetailResidueNum -= entity.getDc_refund_jy();
				
				transferInvitationLoanNum += entity.getDc_trans_jy();
				transferInvitationResidueNum -= entity.getDc_trans_jy();
			}
			
			DCUpdateData dcVo=new DCUpdateData();
			dcVo.setLoanDataId(loanapplyNo);
			dcVo.setBillCode(loanInfo.getBillCode());
			dcVo.setEnsBillLoanNum(ensBillLoanNum);
			dcVo.setEnsBillResidueNum(ensBillResidueNum);
			dcVo.setReceiptLoanNum(receiptLoanNum);
			dcVo.setReceiptResidueNum(receiptResidueNum);
			dcVo.setRefundDetailLoanNum(refundDetailLoanNum);
			dcVo.setRefundDetailResidueNum(refundDetailResidueNum);
			dcVo.setTransferInvitationLoanNum(transferInvitationLoanNum);
			dcVo.setTransferInvitationResidueNum(transferInvitationResidueNum);
			int dcUpate=o2oDCLoanService.updateLandRDate(dcVo);
			if (dcUpate == 0) {
				logger.info("借阅代偿数据保存失败,参数:[{}]",entity.toString());
				throw new RuntimeException();
			}
			//		修改所有借阅信息
			List<ArchiveBorrowEntity> list=archiveBorrowService.queryAllListByloanapplyNo(loanapplyNo);
			for (ArchiveBorrowEntity item : list) {
				item.setDc_ems_sy(ensBillResidueNum);
				item.setDc_receipt_sy(receiptResidueNum);
				item.setDc_refund_sy(refundDetailResidueNum);
				item.setDc_trans_sy(transferInvitationResidueNum);
				
				int result = archiveBorrowService.updateArchiveBorrowRecordById(item);
				if (result == 0) {
					logger.info("setp3:借阅代偿数据保失败msg:[o2o_archive_borrow表修改数据出错],参数:[{}]",item.toString());
					throw new RuntimeException();
				}
			}
			if( borrorw != null){
				borrorw.setDc_ems_sy(ensBillResidueNum);
				borrorw.setDc_receipt_sy(receiptResidueNum);
				borrorw.setDc_refund_sy(refundDetailResidueNum);
				borrorw.setDc_trans_sy(transferInvitationResidueNum);
			}
		}
	}
	
}
